package space.panker916.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;
import space.panker916.pojo.Message;
import space.panker916.pojo.Page;
import space.panker916.pojo.R;
import space.panker916.pojo.User;
import space.panker916.service.MessageService;
import space.panker916.service.UserService;
import space.panker916.utils.HostHolder;

import java.util.*;

import static space.panker916.utils.Constants.*;

@Controller
public class MessageController {
    @Autowired
    private MessageService messageService;

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

    // 私信列表
    @GetMapping("/letter/list")
    public String getLetterList(Model model, Page page) {
        User user = hostHolder.getUser();
        // 分页信息的设置
        page.setLimit(5);
        page.setPath("/letter/list");
        page.setRows(messageService.findConversationCount(user.getId()));
        model.addAttribute("page", page);

        // 会话列表
        List<Message> conversationList = messageService.findConversations(user.getId(), page.getOffset(), page.getLimit());

        // 会话在前端页面展示的形式
        List<Map<String, Object>> conversations = new ArrayList<>();
        for (Message message : conversationList) {
            Map<String, Object> conversationVo = new HashMap<>();
            conversationVo.put("conversation", message);
            conversationVo.put("letterCount", messageService.findLetterCount(message.getConversationId()));
            conversationVo.put("unreadCount", messageService.findLetterUnreadCount(user.getId(), message.getConversationId()));
            int targetId = user.getId() == message.getFromId() ? message.getToId() : message.getFromId();
            conversationVo.put("target", userService.findUserById(targetId));

            conversations.add(conversationVo);
        }

        // 查询未读消息数量（第二个参数为 null ）
        int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(), null);// 私信数量
        int noticeUnreadCount = messageService.findNoticeUnreadCount(user.getId(), null);// 通知数量
        model.addAttribute("letterUnreadCount", letterUnreadCount);
        model.addAttribute("noticeUnreadCount", noticeUnreadCount);

        // 这个就是私信消息列表
        model.addAttribute("conversations", conversations);

        return "/site/letter";
    }

    @GetMapping("/letter/detail/{conversationId}")
    public String getLetterDetail(@PathVariable("conversationId") String conversationId, Model model, Page page) {
        User user = hostHolder.getUser();
        // 分页信息的设置
        page.setLimit(5);
        page.setPath("/letter/detail/" + conversationId);
        page.setRows(messageService.findLetterCount(conversationId));
        model.addAttribute("page", page);

        // 私信列表
        List<Message> letterList = messageService.findLetters(conversationId, page.getOffset(), page.getLimit());
        List<Map<String, Object>> letters = new ArrayList<>();

        // 未读的私信 ID 列表
        List<Integer> ids = new ArrayList<>();

        int targetId = -1;
        for (Message message : letterList) {
            // 1. 设置当前页的私信
            Map<String, Object> letterVo = new HashMap<>();
            letterVo.put("letter", message);
            letterVo.put("fromUser", userService.findUserById(message.getFromId()));
            if (targetId == -1)
                targetId = user.getId() == message.getFromId() ? message.getToId() : message.getFromId();
            letters.add(letterVo);

            // 2. 找到当前页的未读私信
            if (user.getId() == message.getToId() && message.getStatus() == 0) ids.add(message.getId());
        }

        // 将当前页面未读的私信设置为已读
        if (!ids.isEmpty()) messageService.readMessage(ids);

        if (targetId != -1)
            model.addAttribute("target", userService.findUserById(targetId));
        model.addAttribute("letters", letters);

        return "/site/letter-detail";
    }

    @PostMapping("/letter/send")
    @ResponseBody
    public R sendLetter(String toName, String content) {
        User target = userService.findUserByName(toName);
        // 如果目标用户不存在，直接返回提示
        if (target == null) return new R(1, "目标用户不存在");

        // 如果目标用户存在，构建 message
        Message message = new Message();
        int fromId = hostHolder.getUser().getId(), toId = target.getId();
        message.setFromId(fromId);
        message.setToId(toId);
        message.setConversationId(Math.min(fromId, toId) + "_" + Math.max(fromId, toId));
        message.setContent(content);
        message.setCreateTime(new Date());

        messageService.addMessage(message);

        return new R(0);
    }

    @GetMapping("/notice/list")
    public String getNotice(Model model) {
        User user = hostHolder.getUser();

        // 先定义一个数组，然后循环解决？？
        List<String> topicList = new ArrayList<>();
        topicList.add(TOPIC_COMMENT);
        topicList.add(TOPIC_LIKE);
        topicList.add(TOPIC_FOLLOW);

        for (String topic : topicList) {
            Map<String, Object> messageVO = new HashMap<>();
            Message message = messageService.findLatestNotice(user.getId(), topic);
            if (message != null) {
                messageVO.put("message", message);
                String content = HtmlUtils.htmlUnescape(message.getContent());
                HashMap map = JSONObject.parseObject(content, HashMap.class);

                messageVO.put("user", userService.findUserById((Integer) map.get("userId")));
                messageVO.put("entityType", map.get("entityType"));
                messageVO.put("entityId", map.get("entityId"));
                messageVO.put("postId", map.get("postId"));

                int count = messageService.findNoticeCount(user.getId(), topic);
                int unread = messageService.findNoticeUnreadCount(user.getId(), topic);
                messageVO.put("count", count);
                messageVO.put("unread", unread);
            }

            model.addAttribute(topic + "Notice", messageVO);
//            System.out.println(topic + "Notice");
//            System.out.println("messageVO = " + messageVO);
        }

        // 查询未读消息数量（第二个参数为 null ）
        int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(), null);// 私信数量
        int noticeUnreadCount = messageService.findNoticeUnreadCount(user.getId(), null);// 通知数量
        model.addAttribute("letterUnreadCount", letterUnreadCount);
        model.addAttribute("noticeUnreadCount", noticeUnreadCount);

        return "/site/notice";
    }

    @GetMapping("/notice/detail/{topic}")
    public String getNoticeDetail(@PathVariable("topic") String topic, Page page, Model model) {
        User user = hostHolder.getUser();
        page.setLimit(5);
        page.setPath("/notice/detail/" + topic);
        page.setRows(messageService.findNoticeCount(user.getId(), topic));
        model.addAttribute("page", page);

        System.out.println("================================================");
        System.out.println(user.getId() + "  " + topic + "  " + page.getOffset() + "  " + page.getLimit());
        List<Message> noticeList = messageService.findNotices(user.getId(), topic, page.getOffset(), page.getLimit());
        System.out.println("noticeList = " + noticeList);
        List<Map<String, Object>> noticeVoList = new ArrayList<>();
        // 未读的私信 ID 列表
        List<Integer> ids = new ArrayList<>();

        for (Message notice : noticeList) {
            Map<String, Object> map = new HashMap<>();
            // 通知
            map.put("notice", notice);

            // 内容
            String content = HtmlUtils.htmlUnescape(notice.getContent());
            HashMap data = JSONObject.parseObject(content, HashMap.class);

            // 获取未读的文章的id（使这些文章的属性变成已读）
            if (user.getId() == notice.getToId() && notice.getStatus() == 0) ids.add(notice.getId());

            // 内容
            map.put("user", userService.findUserById((Integer) data.get("userId")));
            map.put("entityType", data.get("entityType"));
            map.put("entityId", data.get("entityId"));
            map.put("postId", data.get("postId"));

            // 通知作者
            map.put("fromUser", userService.findUserById(notice.getFromId()));

            // 将信息设置到 VO 里面去
            noticeVoList.add(map);
        }
        // 将当前页面未读的私信设置为已读
        if (!ids.isEmpty()) messageService.readMessage(ids);
        model.addAttribute("notices", noticeVoList);

        System.out.println("noticeVoList = " + noticeVoList);

        return "/site/notice-detail";
    }
}
